Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
Cómo manejar errores con Async y Await [Node.js]

Ya tengo una función escrita con promesas de bluebird y me gustaría reescribirla con async y await. Cuando realicé los cambios, descubrí que anteriormente con las promesas, la declaración de rechazo siempre transfiere el control al bloque de captura de función llamado, aunque el bloque de captura ya está allí en el archivo desde donde estamos rechazando. ¿Cómo manejar esta situación correctamente con async y await?. (Se agregaron comentarios al código para explicar el problema)

con promesa:

 const callingFunc = (req, res) => { return new Promise((resolve, reject) => { // execute request which returns promise functionCall() .then((response) => { let error; try { xml2js(response.body, { explicitArray: false }, (err, result) => { if (err) { return reject(err); /* throws the correct error to catch block of the file from where callingFunc is called*/ } if (!_.isEmpty(result.Response.errorCode)) { return reject(result.Response); /* throws the correct error to the catch block of the file from where callingFunc is called*/ } return resolve(result); }); } catch (e) { error = new Error('xml2js conversion error'); reject(error); } }) .catch((error) => { const Error = new Error('Internal Server Error'); reject(Error); }); }); };

Con asíncrono y espera:

 const callingFunc = (req, res) => { try { const response = await functionCall(); let error; try { xml2js(response.body, { explicitArray: false }, (err, result) => { if (err) { throw (err); /* throws the error to the below catch block and returning xml2js conversion error and changing behaviour*/ } if (!_.isEmpty(result.Response.errorCode)) { throw result.Response; /* throws the error to the below catch block and returning xml2js conversion error and changing behaviour*/ } return result; }); } catch (e) { error = new Error('xml2js conversion error'); throw error; } } catch(error) { const Error = new Error('Internal Server Error'); throw Error; } };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Si functionCall devuelve una promesa, entonces este código es inapropiado...

 return new Promise((resolve, reject) => { // execute request which returns promise functionCall() .then((response) => {

Si xml2js es asíncrono usando devoluciones de llamada, entonces es apropiado envolverlo en una promesa...

 // return a promise that resolves with the result of xml2js async function xml2js_promise(body) { return new Promise((resolve, reject) => { xml2js(body, { explicitArray: false }, (err, result) => { if (err) reject(err); else if (!_.isEmpty(result.Response.errorCode)) reject(result.Response); else resolve(result); }); }); }

Ahora podemos esperar estos. No hay necesidad de anidar los intentos. (Y solo necesita el intento si va a hacer algo en la captura).

 async callingFunction = (req, res) => { try { const response = await functionCall(); } catch (error) { // do something with this error } try { const result = await xml2js_promise(response.body) } catch(error) { // do something with this error } return result; }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda